package com.nursinghome.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.nursinghome.enums.BaseEnum;

public class EnumConverter<T extends Enum<?> & BaseEnum> implements Converter<Integer> {
    private final Class<T> enumType;
    public EnumConverter(Class<T> enumType) {
        this.enumType = enumType;
    }

    @Override
    public Class<Integer> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    /**
     * 这里读的时候会调用
     *
     * @param cellData
     * @return
     */

    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        String excelValue = cellData.getStringValue();
        for (T enumConstant : enumType.getEnumConstants()) {
            if (enumConstant.getExcelValue().equals(excelValue)) {
                return enumConstant.getDbValue();
            }
        }
        throw new IllegalArgumentException("无效的枚举值: " + excelValue);
    }

    /**
     * 这里是写的时候会调用 不用管
     *
     * @return
     */
    @Override
    public WriteCellData<?> convertToExcelData(Integer value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        for (T enumConstant : enumType.getEnumConstants()) {
            if (enumConstant.getDbValue().equals(value)) {
                return new WriteCellData<>(enumConstant.getExcelValue());
            }
        }
        throw new IllegalArgumentException("无效的数据库值: " + value);
    }

}